const app = getApp()
const http = require('../../../utils/util')
const Base64 = require('../../../utils/base')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    note:'',//温馨提示
    codeImg:'',//二维码
	   payClass:'none', //支付成功弹出层显示与隐藏
	   room:{},  //会议事详情
	   otherData:{}, //其他数据
	   hours:0, //一共几个小时
     payTwoClass:'none',//支付成功弹出层显示与隐藏 带二维码
     payThreeClass:"none",//支付前弹出层显示与隐藏
     isShowPayClass:false,//false 普通弹窗 true带二维码
     methodsTxt:'',
	   phoneClass:'none',
	   couponClass:'none', //优惠券显示隐藏
	   page:1, //优惠券分页
	   couponList:[],  //优惠券数据
	   couponIndex:-1, //选中的优惠券索引
	   currentCouponName:'',//选中的优惠券名字
	   orderDetail:{}, //订单信息
	   isPaying:true, //是否正在支付
	   order_id:null, //订单id，去往详情页
	   // second:5, //倒计时
	   // interval:false,
	   conduct:'', //自习室守则
	   subMoney:0, //合计金额
	   couponMoney:'', //优惠金额
	   currentCoupon:'', //选中的优惠券
  },
	
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
    let _this=this
    this.bulletFrame()  
		// if(this.data.payClass=='show'){
		// 	this.setData({
		// 		interval:false,
		// 		second:5
		// 	},()=>{
		// 		let interval= setInterval(()=>{
		// 			if(_this.data.interval){
		// 				clearInterval(interval)
		// 			}
		// 			if(_this.data.second==1){
		// 				clearInterval(interval)
		// 				_this.payhide()
		// 			}
		// 			_this.setData({
		// 				second: --_this.data.second
		// 			})
		// 		},1000)
		// 	})
		// }
  },
  payBefore(e){
    this.setData({
      payThreeClass: "show",
      methodsTxt:e.currentTarget.dataset.pay
    })
  },
  bulletFrame(){
    // 准备参数
    let data = {
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      store_id: this.data.orderDetail.store_id,
    }
      //查询是否当前店显示二维码
      http.post('store/bullet_frame', Base64.encode(JSON.stringify(data))).then((res) => {
          console.log("res====",res)
          if(res.status==1){
              this.setData({
                isShowPayClass:res.result.isShowQrCode,
                note:res.result.note,
                codeImg:res.result.img
              })
          }
      })
      },
	// 自习室守则
	toshowze(){
		this.setData({
			interval:true
		})
		wx.navigateTo({
			url:'/pages/rules/rules?conduct='+JSON.stringify(this.data.conduct)
		})
	},
	
	// 隐藏手机号弹出层
	hidePhone(){
		this.setData({
			phoneClass:'none'
		})
	},
	//获取手机号
	getPhoneNumber(e){
		  this.setData({
			  phoneClass:'none'
		  })
		  if(e.detail.errMsg=='getPhoneNumber:ok'){
		  	wx.login({
				success:(res)=>{
					let data={
						encryptedData:e.detail.encryptedData,
						code:res.code,
						iv:e.detail.iv,
						user_id:wx.getStorageSync('user_id'),
						user_token:wx.getStorageSync('user_token'),
					}
					http.post('user/postPhone',Base64.encode(JSON.stringify(data))).then(res=>{
						if(res.status==1){
							wx.setStorageSync('phone',res.result)
							wx.showToast({
								title:'授权成功',
								icon:'none'
							})
						}else{
							wx.showToast({
								title:res.msg,
								icon:'none'
							})
						}
					})
				}
			})
		  }else{
		  	wx.showToast({
		  		title:'授权失败',
		  		icon:'none'
		  	})
		  }
	},
	
	
	// 支付
     payMethods(e){
      this.setData({
        payThreeClass: "none",
      })
		//判断用户是否授权手机号
		let phone= wx.getStorageSync('phone')
		if(!phone){
		   return this.setData({
				phoneClass:'show'
			})
		}
		
		
		if(!this.data.isPaying) return
		this.setData({
			isPaying:false
		})
		//准备支付接口参数
		let data={
			user_id:wx.getStorageSync('user_id'),
			user_token:wx.getStorageSync('user_token'),
			store_id:this.data.orderDetail.store_id,
			make_start_time:this.data.orderDetail.date,
			make_end_time:this.data.orderDetail.date,
			start_time:this.data.orderDetail.start_hours,
			end_time:this.data.orderDetail.end_hours,
			id:this.data.room.id,
			coupon_type:this.data.currentCoupon.type?this.data.currentCoupon.type:'',
			coupon_id:this.data.currentCoupon.id?this.data.currentCoupon.id:''
		}
		//支付方式
		let methods=this.data.methodsTxt
		if(methods=='wx' && this.data.subMoney!=0){  //微信支付
			this.wxPay(data)
		}else { //储蓄卡支付
			this.cardPay(data)
		}
	},
	//微信支付
	wxPay(data){
		let _this=this
		//支付逻辑
		http.post('store/roomO',Base64.encode(JSON.stringify(data))).then((res)=>{
			if(res.status==1){
				let data=res.result
				wx.requestPayment({
				  timeStamp: data.timeStamp,
				  nonceStr: data.nonceStr,
				  package: data.package,
				  signType: data.signType,
				  paySign: data.paySign,
				  success:(res)=>{
            if(_this.data.isShowPayClass){
              _this.setData({
                payTwoClass:'show',
                order_id:data.order_id,
                conduct:data.conduct
               })
            }else{
              _this.setData({
                payClass:'show',
                order_id:data.order_id,
                conduct:data.conduct
               })
            }
				  },
				  fail:()=>{
					  wx.showToast({
						  title:'支付失败',
						  icon:'none'
					  })
				  },
				  complete:()=>{
					  _this.setData({
					  	isPaying:true
					  })
				  }
				})
			}else{
				_this.setData({
					isPaying:true
				})
				wx.showToast({
					title:res.message,
					icon:'none'
				})
			}
		})
	},
	//银行卡支付
	cardPay(data){
		let _this=this
		http.post('store/roomE',Base64.encode(JSON.stringify(data))).then((res)=>{
			if(res.status==1){
        if(_this.data.isShowPayClass){
          _this.setData({
            payTwoClass:'show',
            order_id: res.result.order_id,
            conduct:res.result.conduct
           })
        }else{
          _this.setData({
            payClass:'show',
            order_id: res.result.order_id,
            conduct:res.result.conduct
           })
        }
			}else{
				this.setData({
					isPaying:true
				})
				if(res.message=='余额不足'){
					wx.showModal({
						title:'提示',
						content:'储蓄卡余额不足',
						success:(res)=>{
							if(res.confirm){
								wx.switchTab({
									url:'/pages/purchase/purchase'
								})
							}
						}
					})
				}else{
					wx.showToast({
						title:res.message,
						icon:'none'
					})
				}
			}
		})
  },
  payThreeHide(){
    this.setData({
      payThreeClass:"none"
    })
  },
	// 隐藏支付成功弹出层
	payhide(){
		getApp().globalData.is_from=true
		let params={
			order_id:this.data.order_id,
			type:2,
			store_id:this.data.orderDetail.store_id
		}
		wx.reLaunch({
			url: '/pages/mine/record/recordorderdetails/recordorderdetails?params='+JSON.stringify(params)
		})
	},
	toOrder(){
		getApp().globalData.is_from=true
		let params={
			order_id:this.data.order_id,
			type:2,
			store_id:this.data.orderDetail.store_id
		}
		wx.reLaunch({
			url: '/pages/mine/record/recordorderdetails/recordorderdetails?params='+JSON.stringify(params)
		})
	},
	//显示优惠券列表
	showCoupon(){
		  this.setData({
			  couponClass:'show'
		  })
	},
	// 隐藏优惠券
	hideCoupon(){
		  this.setData({
		  	couponClass:'hide',
		  })
		  setTimeout(()=>{
			  this.setData({
			  	couponClass:'none'
			  })
		  },200)
	},
	//选择优惠券
	changeCoupon(e){
		  let current=this.data.couponList[e.currentTarget.dataset.index]
		  if(this.data.couponIndex==e.currentTarget.dataset.index){
			  this.setData({
			  	  couponIndex:-1,
				  currentCouponName:''
			  })
		  }else{
			  this.setData({
			  	  couponIndex:e.currentTarget.dataset.index,
				  currentCouponName:current.coupon_name
			  })
		  }
	},
	//获取优惠券信息
	getCouponList(){
		let data={
			user_id:wx.getStorageSync('user_id'),
			user_token:wx.getStorageSync('user_token'),
			page:this.data.page,
			store_id:this.data.otherData.form.id,
			type:2,
			start_time:this.data.orderDetail.date+' '+this.data.orderDetail.start_hours,
			end_time:this.data.orderDetail.date+' '+this.data.orderDetail.end_hours,
			room_num:this.data.room.num
		}
		http.post('user/coupon',Base64.encode(JSON.stringify(data))).then((res)=>{
			if(res.status==1){
				this.setData({
					couponList:res.result
				})
			}else{
				wx.showToast({
					title:'获取优惠券失败',
					icon:'none'
				})
			}
		})
	},
	//优惠券确定按钮
	confirmCoupon(e){
		  let current=this.data.couponList[this.data.couponIndex]
		  
		  //没有选中优惠券时
		  if(!current){
			  this.setData({
				  subMoney:this.data.orderDetail.subtotal,
				  couponMoney:0,
				  currentCouponName:'',
				  couponIndex:-1,
				  currentCoupon:''
			  })
			  return this.hideCoupon()
		  }
		  
		  // 选中相同优惠券时不在计算直接返回
		  if(current.id==this.data.currentCoupon.id){
		  		return this.hideCoupon()
		  }
		  
		  if(current.status!=='未使用'){
		  	wx.showToast({title:'此优惠券不能使用',icon:'none'})
		  	this.setData({
		  		currentCouponName:'',
				couponIndex:-1
		  	})
		  }else{
			//计算优惠后总价
			console.log(current);
			//单价
			let roomPrice=this.data.orderDetail.predict_price 
			//优惠小时数
			let hours=current.hour_num/60
			//预约小时数
			let subHours=this.data.orderDetail.hours
			
			console.log(hours);
			console.log(subHours);
			//总价
			let sub=this.data.subMoney
			
			//优惠金额
			let couponMoney=0
			//优惠后的金额  小于0时代表优惠时长大于预约时长
			let subMoney=0
			//判断优惠时长是否大于预约时长
			if(hours>=subHours){
				couponMoney=sub
				subMoney=0
			}else{
				couponMoney=this.accMul(roomPrice,hours)
				subMoney=this.subtr(sub,couponMoney)
			}
			
			  
		  	this.setData({
		  		couponClass:'hide',
		  		currentCouponName:current.coupon_name,
				couponMoney:couponMoney,
				subMoney:subMoney,
				currentCoupon:current
		  	})
		  	setTimeout(()=>{
		  		this.setData({
		  			couponClass:'none'
		  		})
		  	},200)
		  } 
		  
	},
	//去储值
	tochuzhi(){
		app.globalData.store_id=this.data.orderDetail.store_id
		app.globalData.type_c=4
		app.globalData.seatorderParams=this.data.orderDetail
		wx.switchTab({
			url:'/pages/purchase/purchase'
		})
	},
	//解决js减法精度问题
	subtr(arg1,arg2){ 
	    var r1,r2,m,n; 
	    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
	    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
	    m=Math.pow(10,Math.max(r1,r2)); 
	    n=(r1>=r2)?r1:r2; 
	    return ((arg1*m-arg2*m)/m).toFixed(n); 
	},
	//乘法计算精度
	accMul(arg1,arg2){ 
		var m=0,s1=arg1.toString(),s2=arg2.toString(); 
		try{m+=s1.split(".")[1].length}catch(e){} 
		try{m+=s2.split(".")[1].length}catch(e){} 
		return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
	 },
	
	
	
	
	
	
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	let room=JSON.parse(options.room)
	this.setData({
		room:room.room,
		orderDetail:room,
		subMoney:room.subtotal,
		otherData:app.globalData,
		hours:(app.globalData.se_time.end_stamp-app.globalData.se_time.start_stamp)/3600
	})
	this.getCouponList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})